<template>
    <div class="app-container">
        <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
            <!--部门数据-->
            <pane size="16">
                <el-col>
                    <el-card>
                        <div class="head-container">
                            <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search"
                                style="margin-bottom: 20px" />
                        </div>
                        <div class="head-container">
                            <el-tree :data="deptOptions" :props="{ label: 'label', children: 'children' }"
                                :expand-on-click-node="false" :filter-node-method="filterNode" ref="deptTreeRef"
                                node-key="id" highlight-current default-expand-all @node-click="handleNodeClick" />
                        </div>
                    </el-card>
                </el-col>
            </pane>
            <pane size="84">
                <el-card v-show="showSearch">

                    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="40px">
                        <!-- 工号 -->
                        <el-form-item label="工号" prop="empNo">
                            <el-input v-model="queryParams.empNo" placeholder="请输入工号" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="姓名" prop="fullName">
                            <el-input v-model="queryParams.fullName" placeholder="请输入姓名" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <!-- 岗位 -->
                        <el-form-item label="岗位" prop="positionId" style="width: 250px;">
                            <el-select v-model="queryParams.positionId" placeholder="请选择岗位">
                                <el-option v-for="item in postListData" :label="item.postName"
                                    :value="item.postId"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="职务" prop="title">
                            <el-input v-model="queryParams.title" placeholder="请输入职务/头衔" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
                <el-card style="margin-top: 20px;">
                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button type="primary" plain icon="Plus" @click="handleAdd"
                                v-hasPermi="['web:employee:add']">新增</el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                                v-hasPermi="['web:employee:edit']">修改</el-button>
                        </el-col>
                        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                    </el-row>

                    <el-table v-loading="loading" :data="employeeList" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" align="center" />
                        <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
                        <el-table-column type="index" label="序号" width="55" align="center" />
                        <el-table-column label="工号" align="center" prop="empNo" />
                        <el-table-column label="姓名" align="center" prop="fullName" />
                        <el-table-column label="性别" align="center" prop="gender">
                            <template #default="scope">
                                <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
                            </template>
                        </el-table-column>
                        <!-- <el-table-column label="手机号" align="center" prop="mobile" /> -->
                        <!-- <el-table-column label="邮箱" align="center" prop="email" /> -->
                        <el-table-column label="所属部门" align="center" prop="deptName" />
                        <el-table-column label="岗位" align="center" prop="positionId">
                            <template #default="scope">
                                {{postListData.find(item => item.postId === scope.row.positionId)?.postName
                                    || scope.row.positionId}}
                            </template>
                        </el-table-column>
                        <el-table-column label="职务/头衔" align="center" prop="title" />
                        <!-- <el-table-column label="入职日期" align="center" prop="hireDate" width="180">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.hireDate, '{y}-{m}-{d}') }}</span>
                            </template>
                        </el-table-column> -->
                        <!-- <el-table-column label="用工性质" align="center" prop="workType">
                            <template #default="scope">
                                <dict-tag :options="yonggong_xingzhi" :value="scope.row.workType" />
                            </template>
                        </el-table-column> -->
                        <el-table-column label="人员状态" align="center" prop="status">
                            <template #default="scope">
                                <dict-tag :options="renyuan_zhuangtai" :value="scope.row.status" />
                            </template>
                        </el-table-column>
                        <!-- <el-table-column label="座机" align="center" prop="officePhone" />
                        <el-table-column label="联系地址" align="center" prop="address" /> -->
                        <!-- accountName -->
                        <el-table-column label="绑定账号" align="center" prop="accountName" />
                        <!-- <el-table-column label="绑定账号" align="center" prop="accountId">
                            <template #default="scope">
                                {{accountInfoListData.find(item => item.id === scope.row.accountId)?.name
                                    || scope.row.accountId}}
                            </template>
                        </el-table-column> -->
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
                            <template #default="scope">
                                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                                    v-hasPermi="['web:employee:edit']">修改</el-button>
                                <el-button v-if="scope.row.accountId !== null && scope.row.accountId !== undefined" link
                                    type="primary" icon="Scissor" @click="handleUnbind(scope.row)">解绑账号</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                        v-model:limit="queryParams.pageSize" @pagination="getList" />
                </el-card>
            </pane>
        </splitpanes>
        <!-- 添加或修改系统内全部人员信息；不等同于可登录账号对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="employeeRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="姓名" prop="fullName">
                    <el-input v-model="form.fullName" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-select v-model="form.gender" placeholder="请选择性别">
                        <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                            :value="parseInt(dict.value)"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="form.mobile" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="归属部门" prop="deptId">
                    <el-tree-select v-model="form.deptId" :data="enabledDeptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                        placeholder="请选择归属部门" check-strictly />
                </el-form-item>
                <el-form-item label="岗位" prop="positionId" style="width: 250px;">
                    <el-select v-model="form.positionId" placeholder="请选择岗位">
                        <el-option v-for="item in postListData" :label="item.postName" :value="item.postId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="职务" prop="title">
                    <el-input v-model="form.title" placeholder="请输入职务" />
                </el-form-item>
                <!-- accountInfoListData -->
                <el-form-item label="绑定账号" prop="accountId" style="width: 250px;">
                    <el-select v-model="form.accountId" placeholder="请选择绑定账号">
                        <el-option v-for="item in accountInfoListData" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="入职日期" prop="hireDate">
                    <el-date-picker clearable v-model="form.hireDate" type="date" value-format="YYYY-MM-DD"
                        placeholder="请选择入职日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="用工性质" prop="workType">
                    <el-select v-model="form.workType" placeholder="请选择用工性质">
                        <el-option v-for="dict in yonggong_xingzhi" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="人员状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in renyuan_zhuangtai" :key="dict.value" :label="dict.value">
                            {{ dict.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="座机" prop="officePhone">
                    <el-input v-model="form.officePhone" placeholder="请输入座机" />
                </el-form-item>
                <el-form-item label="联系地址" prop="address">
                    <el-input v-model="form.address" placeholder="请输入联系地址" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Employee">
import { deptTreeSelect, listEmployee, getEmployee, addEmployee, updateEmployee, getPostList, getAccountInfoList, unbind } from "@/api/system/employee";
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import useAppStore from '@/store/modules/app'

// 解绑handleUnbind
const handleUnbind = async (row) => {
    ElMessageBox.confirm(`确定要解绑员工${row.fullName}和账号${row.accountName}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await unbind(row.id)
            ElMessage.success('解绑成功')
            getList()
        } catch (error) {
            console.error('解绑失败失败:', error)
        }
    })
}

// 列表部门回显
function getDeptLabel(targetId) {
    // 遍历当前层级的部门节点
    for (const dept of deptOptions.value) {
        // 若当前节点id匹配，直接返回label
        if (dept.id === targetId) {
            return dept.label;
        }
        // 若存在子节点，递归查询子节点
        if (dept.children && dept.children.length > 0) {
            const childLabel = getDeptLabel(dept.children, targetId);
            // 子节点中找到匹配项，直接返回（避免继续遍历）
            if (childLabel) {
                return childLabel;
            }
        }
    }
    // 未找到匹配id时返回空字符串（可根据需求修改为提示文本）
    return "";
}
const appStore = useAppStore()
const { proxy } = getCurrentInstance();
const { renyuan_zhuangtai, sys_user_sex, yonggong_xingzhi } = proxy.useDict('renyuan_zhuangtai', 'sys_user_sex', 'yonggong_xingzhi');
const deptName = ref("");
const deptOptions = ref(undefined);
const enabledDeptOptions = ref(undefined);
/** 查询部门下拉树结构 */
function getDeptTree() {
    deptTreeSelect().then(response => {
        deptOptions.value = response.data;
        enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
    });
};
/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
    return deptList.filter(dept => {
        if (dept.disabled) {
            return false;
        }
        if (dept.children && dept.children.length) {
            dept.children = filterDisabledDept(dept.children);
        }
        return true;
    });
};
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
    if (!value) return true;
    return data.label.indexOf(value) !== -1;
};
/** 节点单击事件 */
function handleNodeClick(data) {
    queryParams.value.deptId = data.id;
    handleQuery();
};
/** 根据名称筛选部门树 */
watch(deptName, val => {
    proxy.$refs["deptTreeRef"].filter(val);
});

// 账号信息
const accountInfoListData = ref()
const getAccountInfoListData = async () => {
    const res = await getAccountInfoList()
    accountInfoListData.value = res.data
}
// 获取岗位列表下拉框
const postListData = ref()
const getPostListData = async () => {
    const res = await getPostList()
    postListData.value = res.data
}

const employeeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        empNo: null,
        fullName: null,
        deptId: null,
        positionId: null,
        title: null,
    },
    rules: {
        fullName: [
            { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        gender: [
            { required: true, message: "性别 0未知 1-男 2-女不能为空", trigger: "change" }
        ],
        mobile: [
            { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        email: [
            { required: true, message: "邮箱不能为空", trigger: "blur" }
        ],
        deptId: [
            { required: true, message: "所属部门ID不能为空", trigger: "blur" }
        ],
        positionId: [
            { required: true, message: "岗位ID不能为空", trigger: "change" }
        ],
        title: [
            { required: true, message: "职务/头衔不能为空", trigger: "blur" }
        ],
        hireDate: [
            { required: true, message: "入职日期不能为空", trigger: "blur" }
        ],
        workType: [
            { required: true, message: "用工性质 全职-fulltime,兼职-parttime,实习-intern,合同工-contract不能为空", trigger: "change" }
        ],
        status: [
            { required: true, message: "人员状态：在职active/离职leave/停用inactive不能为空", trigger: "change" }
        ],
        officePhone: [
            { required: true, message: "座机不能为空", trigger: "blur" }
        ],
        address: [
            { required: true, message: "联系地址不能为空", trigger: "blur" }
        ],
    }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询系统内全部人员信息；不等同于可登录账号列表 */
function getList() {
    loading.value = true;
    listEmployee(queryParams.value).then(response => {
        employeeList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        empNo: null,
        fullName: null,
        gender: null,
        mobile: null,
        email: null,
        deptId: null,
        positionId: null,
        title: null,
        hireDate: null,
        workType: null,
        status: null,
        officePhone: null,
        address: null,
        remark: null,
        createdAt: null,
        updatedAt: null,
        deleted: null
    };
    proxy.resetForm("employeeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    queryParams.value.deptId = undefined;
    proxy.$refs.deptTreeRef.setCurrentKey(null);
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加系统内全部人员信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value
    getEmployee(_id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改系统内全部人员信息";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["employeeRef"].validate(valid => {
        if (valid) {
            if (form.value.id != null) {
                updateEmployee(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addEmployee(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}


onMounted(() => {
    getPostListData();
    getDeptTree()
    getList();
    getAccountInfoListData();
})
</script>
